package com.github.prontera.service;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.prontera.Shift;
import com.github.prontera.StatusCode;
import com.github.prontera.common.token.PasswordHashUtil;
import com.github.prontera.domain.Client;
import com.github.prontera.domain.OrderRefund;
import com.github.prontera.domain.SystemAccount;
import com.github.prontera.domain.SystemBean;
import com.github.prontera.domain.TalentOrder;
import com.github.prontera.domain.User;
import com.github.prontera.domain.enums.OrderRefundStatusEnum;
import com.github.prontera.domain.enums.OrderStatusEnum;
import com.github.prontera.domain.enums.VipTypeEnum;
import com.github.prontera.persistence.ClientInvitationMapper;
import com.github.prontera.persistence.ClientMapper;
import com.github.prontera.persistence.ClientRentMapper;
import com.github.prontera.persistence.CrudMapper;
import com.github.prontera.persistence.ExtRoleMapper;
import com.github.prontera.persistence.OrderRefundMapper;
import com.github.prontera.persistence.SystemAccountMapper;
import com.github.prontera.persistence.SystemBeanMapper;
import com.github.prontera.persistence.UserMapper;
import com.github.prontera.util.Exceptions;
import com.github.prontera.util.Page;


/**
 * 用户表
 */
@Service
@Transactional
public class UserService extends CrudServiceImpl<User> {

	@Autowired
	private ExtRoleMapper extRoleMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ClientRentMapper clientRentMapper;
	@Autowired
	private OrderRefundMapper orderRefundMapper;
	@Autowired
	private ClientMapper clientMapper;
	@Autowired
	private SystemAccountMapper systemAccountMapper;
	@Autowired
	private SystemBeanMapper systemBeanMapper;
	@Autowired
	private OrderService orderService;
	@Autowired
	private TalentOrderService talentOrderService;
	
	@Autowired
	private ClientInvitationMapper clientInvitationMapper;
	

	@Autowired
	private ConsumeService consumeService;
	
	@Autowired
	public UserService(CrudMapper<User> mapper) {
		super(mapper);
	}

	@Override
	public int insert(User entity) {
		String username = entity.getUsername(); 
		if(null != userMapper.findUsername(username)){
				Shift.fatal(StatusCode.USER_EXISTS);
		}
		try {
			entity.setPassword(PasswordHashUtil.createHash("123456"));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw Exceptions.unchecked(e);
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
			throw Exceptions.unchecked(e);
		}
		entity.setCreateDate(OffsetDateTime.now());//创建时间
		entity.setStatus(0);//初始状态
		super.insert(entity);
		
		Map<String, Object> rMap = new HashMap<String, Object>();
		rMap.put("roleId", entity.getRoleId());
		rMap.put("userId", entity.getId());
		extRoleMapper.insertUserRole(rMap);
		return 1;
	}

	@Override
	public int update(User entity) {
		super.update(entity);
		Map<String, Object> params =new HashMap<String, Object>();
		params.put("userId", entity.getId());
		Long roleId=extRoleMapper.findUserRole(params);
		if(null != roleId){
			extRoleMapper.removeUserId(entity.getId());
		}
		Map<String, Object> rMap = new HashMap<String, Object>();
		rMap.put("roleId", entity.getRoleId());
		rMap.put("userId", entity.getId());
		extRoleMapper.insertUserRole(rMap);
		return 1;
	}
	
	
	public int updatePSD(User user) {
		User insUser = userMapper.get(user.getId());
		
		int resultInt = 0; //操作结果状态 1：修改成功 2：旧密码输入错误
		
		try {
			if (!PasswordHashUtil.validatePassword(user.getOldPWD(), insUser.getPassword())) {
				resultInt = 2;
				return resultInt;
			} else {
				insUser.setPassword(PasswordHashUtil.createHash(user.getPassword()));
				super.update(insUser);
				resultInt = 1;
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} 
		
		return resultInt;
	}
    /**
    * @Title: deleteUser  
    * @Description: 用户管理-删除用户
    * @return
    * @return int  
     */
	public int deleteUser(User entity) {
		entity.setStatus(1);
		super.update(entity);
		Map<String, Object> params =new HashMap<String, Object>();
		params.put("userId", entity.getId());
		Long roleId=extRoleMapper.findUserRole(params);
		if(null != roleId){
			extRoleMapper.removeUserId(entity.getId());
		}
		return 1;
	}
	   /**
	    * @Title: getUser  
	    * @Description: 用户管理-查看用户
	    * @return
	    * @return User  
	     */
		public 	User getUser(User entity) {
			User  user=super.get(entity.getId());
			Map<String, Object> params =new HashMap<String, Object>();
			params.put("userId", entity.getId());
			Long roleId=extRoleMapper.findUserRole(params);
			if (null != roleId) {
				user.setRoleId(user.getRoleId());
			}
			return user;
		}
		 /**
		    * @Title: updateUser  
		    * @Description: 用户管理-修改用户
		    * @return
		    * @return int  
		     */
		public int updateUser(User entity) {
			super.update(entity);
			extRoleMapper.removeUserId(entity.getId());
			Map<String, Object> rMap = new HashMap<String, Object>();
			rMap.put("roleId", entity.getRoleId());
			rMap.put("userId", entity.getId());
			extRoleMapper.insertUserRole(rMap);
			return 1;
		}
		
		 /**
         * 登录首页
         * @param user
         * @return user
         */
		public User loginFind(Long userId) {
			User result=userMapper.findUserRoleName(userId+"");
			return result;
		}
		/**
		 * 禁用用户
		 * @param entity
		 * @return
		 */
		public int banUser(User entity) {
			entity.setId(entity.getId());
			entity.setStatus(2);
			super.update(entity);
			
			return 1;
		}
		
		/**
		 * 启用用户
		 * @param entity
		 * @return
		 */
		public int startUser(User entity) {
			entity.setId(entity.getId());
			entity.setStatus(0);
			super.update(entity);
			
			return 1;
		}
		/**
		 * 根据账号查询用户
		 * @param user
		 * @return
		 */
		public Page<User> accountQuery(User user) {
			long count = userMapper.getAccountQueryList(user);
			Page<User> page = new Page<User>(user.getPageIndex(), user.getPageSize());
			page.setData(userMapper.findAccount(user));
			page.setTotalCount(count);
			return page;
		}
		
		/**
		 * 重置密码
		 * @param entity
		 * @return
		 */
		public int resetPassword(User entity) {
			entity.setId(entity.getId());
			try {
				entity.setPassword(PasswordHashUtil.createHash("123456"));
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
				throw Exceptions.unchecked(e);
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
				throw Exceptions.unchecked(e);
			}
			
			super.update(entity);
			return 1;
		}
		
		/**
		 * 每次登录添加登录时间
		 * @param user
		 * @return
		 */
		public User updateLoginTime(User entity) {
			if(entity.getBeforeLoginDate() == null){
				entity.setBeforeLoginDate(entity.getLoginDate());
			}
			super.update(entity);
			return entity;
		}
		/**
		 * 獲取上一次登陸的ip地址
		 * @param user
		 */
		public void updateLoginIp(User user) {
			if(user.getBeforeLoginIp() == null){
				user.setBeforeLoginIp(user.getLoginIp());
			}
			super.update(user);
		}
		
		/**
		 * 统计首页信息
		 * @return
		 */
		public Map<String, Object> statisticalInformation(Long clientId){
			
			Map<String, Object> map = new HashMap<String, Object>();
			
			OrderRefund orderRefund=new OrderRefund();
			orderRefund.setType(VipTypeEnum.VIP);
			orderRefund.setStatus(OrderRefundStatusEnum.BEING);
			//获取待审核的达人技能数量
			long refundVipSum =  orderRefundMapper.count(orderRefund);
			map.put("refundVipSum", refundVipSum);
			
			orderRefund=new OrderRefund();
			orderRefund.setType(VipTypeEnum.DEPOSIT_AMOUNT);
			orderRefund.setStatus(OrderRefundStatusEnum.BEING);
			//获取待审核的达人技能数量
			long refundBanlanceSum =  orderRefundMapper.count(orderRefund);
			map.put("refundDepositAmountSum", refundBanlanceSum);
			
			SystemAccount systemAccount=new SystemAccount();
			systemAccount.setIsNullAcceptorId(true);
			BigDecimal sum=systemAccountMapper.sum(systemAccount);
			map.put("systemAccountSum", sum);
			
			SystemBean systemBean=new SystemBean();
			BigDecimal systemBeanSum=systemBeanMapper.sum(systemBean);
			map.put("systemBeanSum", systemBeanSum);
			
			//当天注册数
			long registerCount=clientMapper.registerCount();
			map.put("registerCount", registerCount);
			
			//达人订单退单
			TalentOrder talentOrder=new TalentOrder();
			talentOrder.setStatus(OrderStatusEnum.REFUNDS);
			long talendOrderCount=talentOrderService.count(talentOrder);
			map.put("talendOrderCount", talendOrderCount);
			
			//当天订单量
			long orderCount=orderService.orderCount();
			map.put("orderCount", orderCount);
			
			//当天邀请用户数
			long invitationCount=clientInvitationMapper.invitationCountToday();
			map.put("invitationCount", invitationCount);
			
			//当天登录用户数
			long lastLoginCount=clientMapper.lastLoginCount();
			map.put("lastLoginCount", lastLoginCount);
			
			//所有用户数
			long usersCount=clientMapper.count(new Client());
			map.put("usersCount", usersCount);
			
			User client=userMapper.get(clientId);
			//用户名
			map.put("fullname", client.getFullname());
			//用户名
			map.put("beforeLoginDate", client.getBeforeLoginDate());
			return  map;
		}
		
}
